package com.lch.designpattern.delegate.mvc;

import com.lch.designpattern.delegate.mvc.controller.CometController;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.Builder;
import lombok.Data;

/**
 * @author: liuchenhui
 * @create: 2019-06-23 13:03
 **/
public class DispatcherServlet extends HttpServlet {

    private static Map<String, Handler> handleMapping = new HashMap<>();

    @Override
    public void init() {
        Class<?> clazz = CometController.class;

        try {
            handleMapping.put("/getCmdList.json",
                    Handler.builder()
                            .controller(clazz.newInstance())
                            .method(clazz.getMethod("getCmdList", new Class[]{String.class}))
                            .build());
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doDispatcher(req, resp);
    }

    private void doDispatcher(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 1.获取url
        String url = req.getRequestURI();

        // 2.获取Handler
        Handler handler = handleMapping.get(url);
        if (handler == null) {
            resp.getWriter().println("404，未找到页面");
        }

        // 3. 获取参数

        // 4.调用

        // 5.返回
    }
}

@Data
@Builder
class Handler {
    private Object controller;
    private Method method;
}